package day02;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class Demo6 {
    int tickets=100;
    ReentrantLock lock=new ReentrantLock();
    public void buy(){
        String name = Thread.currentThread().getName();
        try {
            if(lock.tryLock(5, TimeUnit.SECONDS))
            {
                try {
                    if (tickets > 0) {
                        tickets--;
                        System.out.println(name + "售票成功，剩余" + tickets);
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    lock.unlock();
                }
            }else{
                System.out.println("5秒都没有票不买了");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //为防止异常发生没有关闭，会写finally在里面
    }
    public static void main(String[] args) {
        Demo6 d=new Demo6();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                d.buy();
            }
        },"窗口一").start();
        new Thread(()->{
            for (int i = 0; i <100 ; i++) {
                d.buy();
            }
        },"窗口二").start();
    }
}
